package cn.lg.soar.common.algorithm;

import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;

import java.math.BigInteger;

import static cn.lg.soar.common.algorithm.SM2Encoder.EC_DOMAIN_PARAMETERS;
import static cn.lg.soar.common.util.data.DataUtil.BASE64DE;

/**
 * SM2解码器
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class SM2Decoder {

    private final SM2Engine sm2Engine;

    public SM2Decoder(byte[] privateKey, SM2Engine.Mode mode) {
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(privateKey), EC_DOMAIN_PARAMETERS);
        sm2Engine = new SM2Engine(mode);
        sm2Engine.init(false, privateKeyParameters);
    }

    public SM2Decoder(byte[] privateKey) {
        this(privateKey, SM2Engine.Mode.C1C3C2);
    }

    /**
     * 解密
     * @param data 数据
     * @return
     */
    public byte[] decrypt(byte[] data) {
        try {
            return sm2Engine.processBlock(data, 0, data.length);
        } catch (InvalidCipherTextException e) {
            throw new AlgorithmException(e);
        }
    }

    /**
     * 解密
     * @param data 数据
     * @return
     */
    public byte[] decryptOfBase64(String data) {
        return this.decrypt( BASE64DE.decode(data) );
    }

}
